package work.soho.proxy.aliyun.parts;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.alidns.model.v20150109.*;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class DdnsLanPart extends BasePart implements IPart{
    /**
     * get client
     * @return
     */
    private IAcsClient getClient() {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", configure.getAccessKeyId(),
                configure.getAccessSecret());
        IAcsClient client = new DefaultAcsClient(profile);
        return client;
    }

    @Override
    public boolean isExist() {
        return getId() != null;
    }

    @Override
    public String getId() {
        try {
            DescribeSubDomainRecordsResponse.Record record = getDnsLanRecode();
            return record.getRecordId();
        } catch (Exception e) {
            //ignore
        }
        return null;
    }

    /**
     * 获取Dns lan ip
     *
     * @return
     */
    public DescribeSubDomainRecordsResponse.Record getDnsLanRecode() {
        try {
            DescribeSubDomainRecordsRequest describeSubDomainRecordsRequest = new DescribeSubDomainRecordsRequest();
            describeSubDomainRecordsRequest.setSubDomain("lan." + configure.getBaseDomain());
            describeSubDomainRecordsRequest.setType("A");
            DescribeSubDomainRecordsResponse describeSubDomainRecordsResponse = getClient().getAcsResponse(describeSubDomainRecordsRequest);
            if(describeSubDomainRecordsResponse.getTotalCount()>0) {
                return describeSubDomainRecordsResponse.getDomainRecords().get(0);
            }
        } catch (Exception e) {
            //ignore
        }
        return null;
    }

    @Override
    public void drop() {

    }

    /**
     * 获取局域网IP地址
     *
     * @return
     */
    private String getLanIp() {
        List<String> list = new ArrayList<String>();
        boolean flag = false;
        int count=0;
        Runtime r = Runtime.getRuntime();
        Process p;
        try {
            p = r.exec("arp -a");
            BufferedReader br = new BufferedReader(new InputStreamReader(p
                    .getInputStream(), "GB2312"));
            String inline;
            while ((inline = br.readLine()) != null) {
                if(inline.indexOf("接口") > -1){
                    String[] parts = inline.split(" ");
                    if(parts.length>=1) {
                        list.add(parts[1]);
                    }
                }
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("ip list size:" + list.size());
        if(list.size()>0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void create() throws AliyunPartsException, ClientException {
        //检查更新还是创建
        DescribeSubDomainRecordsResponse.Record record = getDnsLanRecode();
        if(record == null) {
            AddDomainRecordRequest addDomainRecordRequest = new AddDomainRecordRequest();
            addDomainRecordRequest.setDomainName(configure.getBaseDomain());
            addDomainRecordRequest.setRR("lan");
            addDomainRecordRequest.setType("A");
            addDomainRecordRequest.setValue(getLanIp());
            getClient().getAcsResponse(addDomainRecordRequest);
        } else {
            String lanIp = getLanIp();
            if(!record.getValue().equals(lanIp)) {
                try {
                    //更新IP地址
                    UpdateDomainRecordRequest updateDomainRecordRequest = new UpdateDomainRecordRequest();
                    updateDomainRecordRequest.setRecordId(record.getRecordId());
                    updateDomainRecordRequest.setValue(lanIp);
                    updateDomainRecordRequest.setRR("lan");
                    updateDomainRecordRequest.setType("A");
                    getClient().getAcsResponse(updateDomainRecordRequest);
                } catch (Exception e) {
                    //fixed aliyun The DNS record already exists. bug
                    DeleteDomainRecordRequest deleteDomainRecordRequest = new DeleteDomainRecordRequest();
                    deleteDomainRecordRequest.setRecordId(record.getRecordId());
                    getClient().getAcsResponse(deleteDomainRecordRequest);
                }
            }
        }

    }

    @Override
    public void start() throws AliyunPartsException, ClientException {
        create();
    }

    @Override
    public void configure() throws AliyunPartsException, ClientException {
        create();
    }
}
